import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let vuex = new Vuex.Store({
  state: {
    // 登录的token
    token: null,
    // 当前登录的用户
    user: null
  },
  mutations: {
    /**
     * 退出登录
     * @param state 
     */
    logout(state){
      state.user = null;
      state.token = null;
      localStorage.removeItem("token");
    },
    /**
     * 设置登录状态
     * @param state 
     * @param data 
     */
    setLoginStatus(state,data : {
      user: any,
      token: string
    }){
      (state.token as unknown as string) = data.token;
      state.user = data.user;
      localStorage.setItem("token",data.token);
      localStorage.setItem("user",JSON.stringify(data.user));

    }
  },
  actions: {
  },
  modules: {
  }
})


// 初始化token的信息
let token = localStorage.getItem("token");
let user = localStorage.getItem("user");
// 如果都存在则赋值
if(token&&user){
  vuex.commit("setLoginStatus",{
    token,
    user: JSON.parse(user)
  })
}

export default vuex;